package com.dnjn.happiness.common.core.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;

@Slf4j
public final class RetryUtils {

    public interface Results {
        boolean matching();

        String json();
    }

    public static <V extends Results> V retryOnException(int retryLimit, Callable<V> retryCallable) {
        V v = null;
        int cnt = 0;
        do {
            try {
                v = retryCallable.call();
            } catch (Exception e) {
                log.warn(String.format("retry on {} times v={}; {}", retryLimit, v.json()), e);
            }
            if (null != v && v.matching()) {
                break;
            }
        } while (++cnt > retryLimit);

        return v;
    }
}
